using Fusion.Async.Timers;
using System;
using System.Net;
using UnityEngine;

namespace Fusion.Net
{
    public class HeartBeatsChecker
    {
        float count = 0;
        float interval = 0;

        Action<EndPoint> callback;

        EndPoint ip;

        Timer timer;

        public EndPoint Ip { get => ip; }
        public float Interval 
        { 
            set 
            { 
                lock (this)
                {
                    interval = value; 
                }
            } 
        }

        public HeartBeatsChecker(float interval) : this(null, interval)
        {
        }
        public HeartBeatsChecker(EndPoint ip, float interval)
        {
            this.ip = ip;
            this.interval = interval;
            timer = new Timer().TypeSetter(Timer.InvokeType.Frame).FrequencySetter(1).PersistentSetter(true).TagSetter("HeartBeatsChecker").Invoke(Invoke);
        }

        public void Register(Action<EndPoint> action)
        {
            lock (this)
            {
                callback = action;
            }
        }

        private void Invoke()
        {
            lock (this)
            {
                count+= Time.deltaTime;
                if (count >= interval)
                {
                    callback?.Invoke(ip);
                }
            }
        }

        public void Pause()
        {
            lock (this)
            {
                timer.Pause();
            }
        }

        public void Play()
        {
            lock (this)
            {
                timer.Play();
            }
        }

        public void Reset()
        {
            lock (this)
            {
                count = 0;
            }
        }

        public void Close()
        {
            lock (this)
            {
                timer?.Stop();
                timer = null;
            }
        }
    }
}

